<template>
  <view class="TeamInfo">
    <view class="bg">
      <image class="avatarBg" :src="teamDetail.cover"></image>
    </view>

    <!-- 队伍信息 -->
    <view class="teamInfo">
      <view class="authorAvatar" @click="skipToUserDetail">
        <image :src="teamDetail.author.avatar" class="avatar"></image>
      </view>
      <view class="content">
        <view class="item">队长：{{ teamDetail.author.nickName }}</view>
        <view class="item">队名：{{ teamDetail.title }}</view>
        <view class="item">介绍：{{ teamDetail.introduce }}</view>
        <view class="item"
          >标签：
          <van-tag
            v-for="(item, index) in teamDetail.tags"
            :key="index"
            class="tag"
            size="medium"
            color="#05A47D"
            >{{ item }}</van-tag
          >
        </view>
        <view class="item"
          >人数：{{ teamDetail.userList.length + 1 }} /
          {{ teamDetail.number }}</view
        >
        <view class="item"
          >创建时间：{{
            $formatTime.formatTimeToHHMM(teamDetail.createTime)
          }}</view
        >
      </view>
    </view>

    <!-- 队员信息 -->
    <view class="teamMember">
      <view class="title">队伍成员</view>
      <view
        class="memberItem animate__animated animate__bounceInRight"
        v-for="item in teamMember"
        :key="item._openid"
        @click="skipToTeamUserDetail(item)"
      >
        <image :src="item.avatar" class="avatar"></image>
        <view class="userInfo">
          <view>{{ item.nickName }}</view>
          <view style="font-size: 26rpx; margin: 10rpx 0">{{
            item.introduce
          }}</view>
          <view class="tagBox">
            <van-tag
              v-for="(i, index) in item.tags"
              class="tag"
              color="#05A47D"
              size="medium"
              :key="index"
              >{{ i }}</van-tag
            >
          </view>
        </view>
      </view>
      <EmptyBox v-if="!teamMember.length" />
      <view class="operator">
        <van-button
          color="linear-gradient(to right, #05A47D, #aaa)"
          size="small"
          block
          :disabled="btnIndex !== 0 || btnLoading"
          v-if="userInfo._openid !== teamDetail._openid"
          @click="applyAddTeam"
          >{{ btnContent[btnIndex] }}</van-button
        >
      </view>
    </view>

    <!-- password -->
    <view class="passwordMask" v-if="showPassword">
      <view class="passwordBox animate__animated animate__bounceIn">
        <view class="Ptitle">请输入密码</view>
        <view class="form">
          <text>密码:</text>
          <view class="inputBox">
            <input type="password" v-model="teamPassword" />
          </view>
        </view>
        <view class="btnGroup">
          <van-button color="#aaa" size="small" @click="showPassword = false"
            >取消</van-button
          >
          <van-button color="#05A47D" size="small" @click="confirmPassword"
            >确定</van-button
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import EmptyBox from "../../components/public/EmptyBox.vue";
import { mapState } from "vuex";
import { TeamMessage } from "../../utils/messageController";
export default {
  components: {
    EmptyBox,
  },
  data() {
    return {
      teamDetail: {},
      teamPassword: "",
      showPassword: false,
      btnContent: ["申请加入", "已申请加入", "已满员", "已是成员"],
      btnIndex: 0,
      btnLoading: false,
    };
  },
  computed: { ...mapState(["userInfo", "teamLeader", "teamMember"]) },
  onLoad(options) {
    this.teamDetail = JSON.parse(decodeURIComponent(options.teamDetail));
    this.getTeamLeaderInfo();
    this.getTeamMember();
    this.judgeApplyStatus();
  },

  methods: {
    // 跳转至队长信息详情页
    skipToUserDetail() {
      uni.navigateTo({
        url: `/pages/UserInfo/UserInfo?userDetail=${encodeURIComponent(
          JSON.stringify(this.teamLeader)
        )}`,
      });
    },

    // 跳转至队员信息详情页
    skipToTeamUserDetail(item) {
      uni.navigateTo({
        url: `/pages/UserInfo/UserInfo?userDetail=${encodeURIComponent(
          JSON.stringify(item)
        )}`,
      });
    },

    // 获取队长信息
    async getTeamLeaderInfo() {
      const userId = this.teamDetail._openid;
      await this.$store.dispatch("getUserInfo", { type: 1, userId });
    },

    // 获取队伍成员信息
    async getTeamMember() {
      const userList = this.teamDetail.userList;
      this.$store.commit("clearTeamMember"); // 先清空之前残留的人员数据
      if (userList.length) {
        for (let i = 0; i < userList.length; i++) {
          const userId = userList[i];
          await this.$store.dispatch("getUserInfo", { type: 2, userId });
        }
      }
    },

    // 判断申请状态
    judgeApplyStatus() {
      // 判断队伍是否已经满员
      if (this.teamDetail.userList.length + 1 === this.teamDetail.number) {
        this.btnIndex = 2;
        return;
      }
      // 如果用户已经是其中的一员，则清除申请缓存
      if (this.teamDetail.userList.includes(this.userInfo._openid)) {
        this.removeApplyStatus(this.teamDetail._id);
        this.btnIndex = 3;
        return;
      }
      // 如果被拒绝，则清除申请缓存，可以进行重新申请
      if (this.teamDetail.refuseList.includes(this.userInfo._openid)) {
        this.removeApplyStatus(this.teamDetail._id);
        this.btnIndex = 0;
        return;
      }

      // 判断是否已经申请过这个队伍
      if (!this.judgeIsApply(this.teamDetail._id)) {
        this.btnIndex = 1;
        return;
      }
    },

    // 申请加入队伍
    applyAddTeam() {
      if (!this.userInfo.avatar.length || !this.userInfo.nickName.length) {
        uni.showToast({
          icon: "error",
          title: "请先进行登录",
        });
        return;
      }
      if (!this.userInfo.joinTeam.length >= 3) {
        uni.showToast({
          icon: "error",
          title: "最多加入3支",
        });
        return;
      }
      const meId = this.userInfo._openid; // 判断是否已是成员
      if (this.teamDetail.userList.includes(meId)) {
        uni.showToast({
          icon: "error",
          title: "你已是队伍成员",
        });
        return;
      }
      if (!this.handlePassword()) {
        this.sendApplyTeamMessage();
      }
    },

    // 确认发送申请加入队伍的消息
    async sendApplyTeamMessage() {
      this.btnLoading = true;
      // 整合发送消息内容
      const teamMessageBox = new TeamMessage(),
        receiveId = this.teamDetail._openid,
        teamName = this.teamDetail.title,
        applyName = this.userInfo.nickName,
        teamId = this.teamDetail._id,
        item = teamMessageBox.messageForApply({
          receiveId,
          teamName,
          applyName,
          teamId,
        });
      this.btnIndex = 1;
      this.setApply(teamId);
      try {
        await this.subscribeMessage();
        // 向队长发送消息等待同意
        await this.$store.dispatch("m_message/sendMessage", item);
        uni.showToast({
          icon: "success",
          title: "已提交申请",
        });
      } catch (err) {
        uni.showToast({
          icon: "error",
          title: "申请失败",
        });
      }

      this.btnLoading = false;
    },

    // 获取发送订阅消息的权限
    subscribeMessage() {
      return new Promise((resolve, reject) => {
        wx.requestSubscribeMessage({
          tmplIds: ["YUNh7Ka_IlQwxaYN6zc06yC4vmzyNhf7iU88PRFPEIw"],
          success(res) {
            console.log("订阅结果：", res);
            resolve("success");
          },
          fail(res) {
            console.log("订阅结果：", res);
            reject("error");
          },
        });
      });
    },

    // 判断是否存在密码
    handlePassword() {
      if (this.teamDetail.password.trim().length) {
        this.showPassword = true;
        return true;
      }
      return false;
    },

    // 判断密码是否正确
    confirmPassword() {
      if (this.teamDetail.password !== this.teamPassword) {
        uni.showToast({
          icon: "error",
          title: "密码错误",
        });
      } else {
        // 正确直接进行发送申请请求
        this.showPassword = false;
        this.sendApplyTeamMessage();
      }
    },

    // 设置是否申请的标志
    setApply(teamId) {
      const applyList = wx.getStorageSync("apply") || [];
      applyList.push(teamId);
      wx.setStorageSync("apply", applyList);
    },
    // 判断用户是否已经申请过加入队伍
    judgeIsApply(teamId) {
      const applyList = wx.getStorageSync("apply");
      if (applyList.includes(teamId)) {
        return false;
      }
      return true;
    },

    // 移除申请过的标志
    removeApplyStatus(teamId) {
      let applyList = wx.getStorageSync("apply") || [];
      applyList = applyList.filter((item) => item !== teamId);
      wx.setStorageSync("apply", applyList);
    },
  },
};
</script>

<style lang="scss">
.TeamInfo {
  width: 100vw;
  position: relative;
  .tag {
    margin-right: 10rpx;
  }
  .bg {
    width: 100%;
    height: 450rpx;
    .avatarBg {
      width: 100%;
      height: 100%;
      filter: blur(5rpx);
    }
  }
  .teamInfo {
    position: relative;
    background-color: #fff;
    padding: 20rpx;
    color: #999;
    font-size: 28rpx;

    .authorAvatar {
      position: absolute;
      left: 50rpx;
      top: -120rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 170rpx;
      height: 170rpx;
      border-radius: 50%;
      overflow: hidden;
      background-color: #fff;

      .avatar {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
      }
    }
    .content {
      margin-top: 30rpx;
      .item {
        margin-bottom: 15rpx;
      }
    }
  }
  .teamMember {
    margin-top: 10rpx;
    background-color: #fff;
    padding: 20rpx;
    .title {
      font-size: 36rpx;
      text-align: center;
      margin-bottom: 20rpx;
    }

    .memberItem {
      box-sizing: border-box;
      padding: 10rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #999;
      border-bottom: 1rpx solid #eee;
      .avatar {
        width: 130rpx;
        height: 130rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }
    }
    .operator {
      width: 70%;
      margin: 0 auto;
      margin-top: 20rpx;
    }
  }

  .passwordMask {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
    background-color: rgba(0, 0, 0, 0.7);
    transition: all 0.5s;
    .passwordBox {
      padding: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: #fff;
      border-radius: 10rpx;
      .form {
        display: flex;
        align-items: center;
        .inputBox {
          padding: 5rpx 10rpx;
          border: 1px solid #eee;
          border-radius: 5rpx;
          margin-left: 10rpx;
        }
      }

      .Ptitle {
        font-size: 32rpx;
        margin-bottom: 20rpx;
      }
      .btnGroup {
        margin-top: 20rpx;
        width: 80%;
        display: flex;
        justify-content: space-around;
      }
    }
  }
}
</style>

<style>
page {
  background-color: #fff;
  height: 100%;
}
</style>
